<?php

class User_AccountController extends User_Library_Controller_Action
{
    public function init()
    {
        parent::init();
        $this->_model = new Model_User();
    }

    /**
     * @todo Redirect to home page
     * @return void
     */
    public function indexAction() {
    }
    
    public function profileAction() {
        // redirect to login page if user not login yet
        if (empty($this->view->userProfile)) {
            $urlOptions = array(
                'module' => 'user',
                'controller' => 'auth',
                'action' => 'login'
            );
            $this->_helper->redirector->gotoRoute($urlOptions);
        }
    }
    
    public function resetPasswordSuccessfulAction() {
        
    }
    
    public function forgotPasswordSubmitedAction() {
    
    }

    public function resetPasswordAction()
    {
        $this->_form = new User_Form_ResetPass();
        $msg = array(
            'result' => 'error',
            'message' => $this->view->translate('ACCOUNT_FORGOT_PASSWORD_INVALID_PARAMS_REQUEST')
        );

        if ($this->getRequest()->isPost()) {
            if ($this->_form->isValid($this->getRequest()->getPost())) {
                $email = $this->getRequest()->getParam('email_recover');
                $data = $this->_model->search('email', $email);
                if(isset($data[0])) {
                    $user = $data[0];
                    $user->setPassword(md5($this->getRequest()->getParam('password')));
                    $user->setResetPasswdCode(' ');
                    $id = $user->save();
                    $msg = array(
                        'result' => 'success',
                        'message' => ''
                    );
                    $this->_forward('reset-password-successful', 'account', 'user');
                }
            }
        }

        $params = $this->getRequest()->getParams();
        if(isset($params['email']) && isset($params['code'])) {
            $email = base64_decode($params['email']);
            $code = $params['code'];

            $data = $this->_model->search('email', $email);
            if(isset($data[0])) {
                $user = $data[0];
                if($user->getResetPasswdCode() == $code) {
                    $this->_form->getElement('email_recover')->setValue($email);
                    $this->view->form = $this->_form;
                    $msg = array(
                        'result' => 'success',
                        'message' => ''
                    );
                }
            }
        }
        
        if($msg['result'] == 'error') {
            $this->_forward('forgot-password', 'account', 'user', array('error_message' => $msg['message']));
        }
    }

    public function forgotPasswordAction()
    {
        $this->_form = new User_Form_ForgotPass();

        if ($this->getRequest()->isPost()) {
            $tableName = $this->_model->getMapper()->getDbTable()->getTableName();

            $email = $this->_form->getElement('email');
            $email->addValidator('Db_RecordExists', false, array('table' => $tableName, 'field' => 'email'));
            $email->getValidator('Db_RecordExists')->setMessage($this->view->translate('EMAIL_NOT_REGISTERED'));

            if ($this->_form->isValid($this->getRequest()->getPost())) {
                $data = $this->_model->search('email', $email->getValue());
                if(isset($data[0])) {
                    $resetPasswordCode = $this->generateCode('forgot-password');
                    $user = $data[0];
                    $user->setResetPasswdCode($resetPasswordCode);
                    $user->save();
                    $fullname = $user->getFullname();
                    $this->sendMailForgotPassword($email->getValue(), $fullname, $resetPasswordCode);
                    $this->_forward('forgot-password-submited', 'account', 'user');
                }
            }
        }

        $params = $this->getRequest()->getParams();
        if(isset($params['error_message'])) {
            $this->view->assign('error_message', $params['error_message']);
        }

        $this->view->form = $this->_form;
    }

    private function sendMailForgotPassword($email, $fullname, $code)
    {
        try {
            $urlOptions = array(
                'module' => 'user',
                'controller' => 'account',
                'action' => 'reset-password',
                'email' => base64_encode($email),
                'code' => $code);
            $forgotPasswordLink = $this->view->url($urlOptions, 'default', false);

            $logger = Zend_Registry::get('logger');
            $logger->log($forgotPasswordLink, Zend_Log::DEBUG);

            $view = new Zend_View();
            $view->setScriptPath(APP_PATH . DS . 'layouts');
            $view->fullname = $fullname;
            $view->forgotPasswordURL = $forgotPasswordLink;

            $mail = new Zend_Mail('utf-8');
            $mail->addTo($email, $fullname);
            $mail->setSubject($this->view->translate('ACCOUNT_FORGOT_PASSWORD_SUBJECT'));
            $body = $view->render('emailtemplate/account-forgot-password.phtml');
            $mail->setBodyHtml($body);
            $mail->send();
        }
        catch (Zend_Exception $e) {
            $logger = Zend_Registry::get('logger');
            $params = $this->getRequest()->getParams();
            $message = $e->getMessage() . "\n" . $e->getTraceAsString() . "\n Param: \n" . var_export($params, true) . "\n";
            $logger->log($message, Zend_Log::DEBUG);
        }
    }
}